package com.dxd.onlineshop.service;

import com.dxd.onlineshop.mapper.ProductMapper;
import com.dxd.onlineshop.mapper.goodsMapper;
import com.dxd.onlineshop.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private goodsMapper goodsMapper;

    // 搜索商品
    public List<Product> searchProducts(String query, Integer categoryId) {
        return productMapper.searchProducts(query, categoryId);
    }

    // 获取所有商品
    public List<Product> getAllProducts() {
        return goodsMapper.getProducts();
    }

    // 根据ID获取商品
    public Product getProductById(Integer id) {
        return goodsMapper.getProductById(id);
    }

    // 添加新商品
    @Transactional
    public Product addProduct(Product product) {
        goodsMapper.addProduct(product);
        return product; // 返回添加后的商品（包含生成的ID）
    }

    // 更新商品信息
    @Transactional
    public boolean updateProduct(Product product) {
        return goodsMapper.updateProduct(product) > 0;
    }

    // 更新商品库存
    @Transactional
    public boolean updateProductStock(Integer productId, Integer newStockQuantity) {
        return goodsMapper.updateProductStock(productId, newStockQuantity) > 0;
    }

    // 删除商品
    @Transactional
    public boolean deleteProduct(Integer id) {
        return goodsMapper.deleteProduct(id) > 0;
    }

    // 根据分类ID获取商品
    public List<Product> getProductsByCategoryId(Integer categoryId) {
        return goodsMapper.getProductsByCategoryId(categoryId);
    }

    // 减少商品库存（用于下单）
    @Transactional
    public boolean reduceStock(Integer productId, Integer quantity) {
        return goodsMapper.reduceStock(productId, quantity) > 0;
    }
}